package list.impl;

import iterator.MyIterator;
import iterator.impl.MyArrayListIterator;
import list.MyList;

/**
 * 随便写的一个ArrayList
 */
public class MyArrayList<T> implements MyList<T> {

    private Object[] Element;

    private int capacity;

    private int length;

    private final int DefaultSize = 10;

    public MyArrayList() {
        this.Element = new Object[DefaultSize];
        this.capacity = DefaultSize;
        this.length = 0;
    }

    public MyArrayList(int capacity) {
        this.capacity = capacity;
        this.Element = new Object[this.capacity];
        this.length = 0;
    }

    @Override
    public MyIterator<T> iterator() {
        return new MyArrayListIterator<T>(this);
    }

    @Override
    public boolean add(T o) {
        if (this.length < this.capacity) {
            this.Element[this.length++] = o;
            return true;
        }
        // 扩容
        this.capacity = this.capacity + (this.capacity / 2);
        Object[] newElement = new Object[this.capacity];
        System.arraycopy(this.Element, 0, newElement, 0, this.length);
        return true;
    }

    @Override
    public int size() {
        return this.length;
    }

    @Override
    public boolean isEmpty() {
        return this.size() == 0;
    }

    @Override
    public boolean remove(int index) {
        if (index >= this.length) throw new IndexOutOfBoundsException("下标越界");
        if (index == this.length - 1) {
            this.length--;
            return true;
        }
        Object[] value = this.Element;
        for (int i = index + 1; i < this.length; i++) {
            value[i - 1] = value[i];
        }
        return true;
    }

    @Override
    public T get(int index) {
        if (index >= this.length) throw new IndexOutOfBoundsException("下标越界");
        return (T) this.Element[index];
    }
}
